package com.stox.ui.javafx.launcher;

import java.io.FileNotFoundException;

import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Log4jConfigurer;

import com.stox.ui.javafx.core.util.ExceptionHandler;
import com.stox.ui.javafx.core.widget.StoxStage;

public class ApplicationContextLoaderRunnable implements Runnable{

	private Stage primaryStage;
	private ConfigurableApplicationContext applicationContext;
	
	public void loadApplicationContext(Stage stage) {
		this.primaryStage = stage;

		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
		
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				if(null == applicationContext) return;
				applicationContext.stop();
				applicationContext.close();
			}
		});
		
		showSplashScreen();
		
		new Thread(this).start();
	}
	
	private void showSplashScreen(){
		primaryStage.setMaximized(true);
		primaryStage.initStyle(StageStyle.TRANSPARENT);
		Group group = new Group();
		Scene scene  = new Scene(group, Color.TRANSPARENT);
		primaryStage.setScene(scene);
		group.getChildren().add(createSplashNode());
		primaryStage.show();	
	}
	
	private Node createSplashNode(){
		BorderPane pane = new BorderPane();
		pane.setStyle("-fx-background-color:radial-gradient(center 90% -40%, radius 200%, white 20%, rgb(100,100,255) 80%);"
				+ " -fx-border-radius: 50; -fx-background-radius: 50; -fx-min-width:600px; -fx-min-height:400px;-fx-content-display:bottom;");
		Label label = new Label("    Stox");
		label.setStyle("-fx-background-color:transparent; -fx-text-fill:white; -fx-font-family:'Garamond'; -fx-font-size:50; -fx-font-weight:bolder;");
		pane.setBottom(label);
		Rectangle2D visualBounds = Screen.getPrimary().getVisualBounds();
		pane.setLayoutX((visualBounds.getMinX()+visualBounds.getMaxX())/2 - 300);
		pane.setLayoutY((visualBounds.getMinY()+visualBounds.getMaxY())/2 - 200);
		return pane;
	}
	
	private void launchApplication(){
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				try {
					Log4jConfigurer.initLogging("classpath:configuration/log/log4j.properties");
				} catch (FileNotFoundException e) {}
				applicationContext = new CachingClassPathXmlApplicationContext("configuration/spring/application-context-main.xml");
				StoxStage stoxStage = applicationContext.getBean(StoxStage.class);
				stoxStage.show();
				primaryStage.hide();
			}
		});
	}
	
	@Override
	public void run() {
		launchApplication();
	}
	
}
